﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Windows.Forms;
using Ledict.ConditionExtract.Base;
using Ledict.ConditionExtract.BLL;
using Ledict.ConditionExtract.Common;
using Ledict.ConditionExtract.Model;
using Ledict.Utility.Frm.Model;
using Ledict.Utility.Msg;
using System.Collections;
using System.Text;
using Ledict.Utility.Frm;

namespace Ledict.ConditionExtract.Frm.NodeTree
{

    /// <summary>
    /// 添加信息单元
    /// </summary>
    public partial class FrmInfoUnit : BaseForm
    {
        #region 构造单例
        private readonly static object _lock = new object();

        private static FrmInfoUnit _instance;

        public static FrmInfoUnit Instance
        {
            get
            {
                if (_instance == null || _instance.IsDisposed)
                {
                    lock (_lock)
                    {
                        if (_instance == null || _instance.IsDisposed)
                        {
                            _instance = new FrmInfoUnit();
                        }
                    }
                }
                return _instance;
            }
        }

        private FrmInfoUnit()
        {
            InitializeComponent();

        }

        #region 成员变量

        /// <summary>
        /// 父窗体选择树节点
        /// </summary>
        public TreeNode ClickNode { get; set; }

        /// <summary>
        /// 二级节点子类型名称（用于判断启用默认配置项）
        /// </summary>
        public string CodeSubType { get; set; }

        /// <summary>
        /// 一级节点类型
        /// </summary>
        public string CCNodeType { get; set; }


        //添加来源表
        public DataTable sysExpressSourceTable = new DataTable();

        NewIDBLL newid = new NewIDBLL();
        AboutRegexBLL regexbll = new AboutRegexBLL();
        Express_SourceBLL SourceBLL = new Express_SourceBLL();
        ExpressGroupSituationBLL expressgroupsituationbll = new ExpressGroupSituationBLL();
        ExpressSourceDefaultSettingsBLL esd = new ExpressSourceDefaultSettingsBLL();
        SYS_InfoElementsBLL trbll = new SYS_InfoElementsBLL();
        private string es_id = string.Empty;

        //来源默认配置表
        public DataTable sysExpressSourceDefaultTable = new DataTable();

        //获取文书类型
        private LogicCaseTypeDocTypeRelationBLL caseTypeDocTypeRelationBll = new LogicCaseTypeDocTypeRelationBLL();
        private SYS_CaseType_DocType_LogicParagBLL sysCaseTypeDocTypeParagBll = new SYS_CaseType_DocType_LogicParagBLL();
        //DataGridViewCheckBoxColumn colCB = new DataGridViewCheckBoxColumn();
        //DatagridViewCheckBoxHeaderCell cbHeader = new DatagridViewCheckBoxHeaderCell();

        #endregion

        /// <summary>
        /// 窗体加载 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void FrmInfoUnit_Load(object sender, EventArgs e)
        {
            //加载 第一级来源树+相关信息单元
            LoadSourceTree();
            //加载批量选择节点类型，参数为空则加载所有节点类型，不为空，则加载父节点下的子节点的所有类型
            if (CCNodeType.Contains("t"))
            {
                LoadCaseCouseListItem1(ClickNode.Tag.ToString());
            }
            else
            {
                LoadCaseCouseListItem(ClickNode.Tag.ToString());
            }
            //获取信息来源（绑定的该节点已经建立的信息单元）
            //LoadRegRelation(ClickNode.Tag.ToString());
            //加载用途列表
            LoadPurposeList();
            //获取版本列表
            LoadVersionList();
            groupBox1.Enabled = false;
            Tree_Source.ForeColor = System.Drawing.Color.Gray;
            groupBox9.Enabled = false;
            // groupBox4.Enabled = false;
            this.Text = ClickNode.Text + "添加来源规则";

            sysExpressSourceTable.Columns.Add("ES_ID", typeof(string));
            sysExpressSourceTable.Columns.Add("CC_ID", typeof(string));
            sysExpressSourceTable.Columns.Add("Source_ID", typeof(string));
            sysExpressSourceTable.Columns.Add("Source_ParagraphID", typeof(string));
            sysExpressSourceTable.Columns.Add("Source_Name", typeof(string));
            sysExpressSourceTable.Columns.Add("Source_ParagraphName", typeof(string));
            sysExpressSourceTable.Columns.Add("CC_RegexInfoCode", typeof(string));
            sysExpressSourceTable.Columns.Add("ES_Purpose", typeof(string));
            sysExpressSourceTable.Columns.Add("Source_TextType", typeof(string));
            sysExpressSourceTable.Columns.Add("EI_Name", typeof(string));
            sysExpressSourceTable.Columns.Add("ES_PurposeName", typeof(string));
            sysExpressSourceTable.Columns.Add("Source_TextTypeName", typeof(string));
            sysExpressSourceTable.Columns.Add("IsML", typeof(string));

            dgvFrmInfoUnit.AutoGenerateColumns = false;
            dgvFrmInfoUnit.ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;

            this.Tree_Source.HideSelection = false;
            this.Tree_Source.DrawMode = TreeViewDrawMode.OwnerDrawText;
            this.Tree_Source.DrawNode += new DrawTreeNodeEventHandler(treeView1_DrawNode);

            //判断是二级类型还是一级类型           
            string nodeType = CodeSubType == "0" || CodeSubType == null ? CCNodeType : CodeSubType;
            int level;
            if (nodeType.Contains("t"))
            {
                level = 3;
            }
            else
            {
                level = CodeSubType == "0" ? 1 : 2;
            }
            sysExpressSourceDefaultTable = esd.GetExpressSourceDefaultSettingsData(nodeType, level);
            if (sysExpressSourceDefaultTable != null && sysExpressSourceDefaultTable.Rows.Count > 0)
            {
                DataTable disTable = new DataTable();
                disTable.Columns.Add("ES_PurposeName");
                disTable.Columns.Add("ES_PurposeID");
                foreach (DataRow dr in sysExpressSourceDefaultTable.Rows)
                {
                    DataRow drr = disTable.NewRow();
                    drr["ES_PurposeID"] = dr["ES_PurposeID"];
                    drr["ES_PurposeName"] = dr["ES_PurposeName"];
                    if (disTable.Select("ES_PurposeID='" + dr["ES_PurposeID"] + "'").Length == 0)
                        disTable.Rows.Add(drr);
                }
                ckbInfoUnit.Enabled = true;
                ckbInfoUnit.Checked = true;
                chkLstBox_Purpose.DataSource = disTable;
                chkLstBox_Purpose.DisplayMember = "ES_PurposeName";
                chkLstBox_Purpose.ValueMember = "ES_PurposeID";
                chkLstBox_Purpose.SelectedIndex = -1;
            }
            else
            {
                ckbInfoUnit.Enabled = false;
            }
            //sysExpressSourceTable.Columns.Add("Select");
            //colCB.HeaderCell = cbHeader;
            //dgvFrmInfoUnit.Columns.Insert(0, colCB);
            //cbHeader.OnCheckBoxClicked += new CheckBoxClickedHandler(cbHeader_OnCheckBoxClicked);

            //dgvFrmInfoUnit.DataSource = sysExpressSourceTable;
            //this.colCB.DataPropertyName = "Select";
        }

        private void cbHeader_OnCheckBoxClicked(bool Status)
        {
            for (int i = 0; i < dgvFrmInfoUnit.Rows.Count - 1; i++)
            {
                sysExpressSourceTable.Rows[i]["Select"] = Status;
            }
        }
        #endregion




        #region Method

        #region 信息来源

        private TreeNode findParentNode(TreeNode node)
        {
            if (node.Parent == null)
            {
                return node;
            }
            else
            {
                return findParentNode(node.Parent);
            }
        }

        /// <summary>
        /// 加载 第一级来源树+相关信息单元
        /// </summary>
        private void LoadSourceTree()
        {
            TreeDataBLL trbll = new TreeDataBLL();
            DataTable dt = new DataTable();
            if (findParentNode(ClickNode).Text == "刑事罪名")
            {
                dt = trbll.GetSourceTree_New("CT_Code in('a1','jb1','ja1') and CD_DocType=1 and CDR_IsAnalysableDoc=1");
            }
            else if (findParentNode(ClickNode).Text == "民事案由")
            {
                //dt = trbll.GetSourceTree_New("CT_Code in ('b1','ldzc') and (CD_DocType=1 and CDR_IsAnalysableDoc=1) or CD_DocType=5");
              dt = trbll.GetSourceTree_New("CT_Code='b1' and (CD_DocType=1 and CDR_IsAnalysableDoc=1) or CD_DocType=5");
            }
            else if (findParentNode(ClickNode).Text == "行政执法")
            {
                dt = trbll.GetSourceTree_New("CT_Code='xzzf' and (CD_DocType=1 and CDR_IsAnalysableDoc=1) or CD_DocType=5");
            }
            #region MyRegion
            //if (dt != null && dt.Rows.Count > 0)
            //{
            //var list = dt.AsEnumerable().ToList();
            //if ((findParentNode(ClickNode).Text == "刑事罪名"))
            //{
            //    list1 = dt.Select("CT_Code in('a1','jb1','ja1') and CD_DocType=1 and CDR_IsAnalysableDoc=1");
            //}
            //else
            //{
            //    list1 = dt.Select("CT_Code='b1' and (CD_DocType=1 and CDR_IsAnalysableDoc=1) or CD_DocType=5");
            //}
            //var whereList =
            //    list.Where(
            //        x =>
            //            (x[1].ToString() == "a1" || x[1].ToString() == "b1") &&
            //            (x[6].ToString() == "1" || x[6].ToString() == "5") &&
            //            (x[13].ToString() == "1" || x[13] == DBNull.Value)).ToList();
            //DataTable dt = trbll.GetSourceTree_New();
            //DataRow[] arrayDr = dt.Select();

            //  foreach (DataRow caseTreeNodeRode in list.Where(x => (x[1].ToString() == "a1" || x[1].ToString() == "b1") && (x[6].ToString() == "1" || x[6].ToString() == "5") && (x[13].ToString() == "1" || x[13] == DBNull.Value)))

            #endregion   
            if (dt != null && dt.Rows.Count > 0)
            {
                foreach (DataRow caseTreeNodeRode in dt.Rows)
                {
                    TreeNode node = new TreeNode
                    {
                        Text = LdFormat.ObjectToString(caseTreeNodeRode["CD_Name"]),//CD_Name,名称
                        Tag = caseTreeNodeRode["CD_ID"] + "," + caseTreeNodeRode["CD_CODE"]//CD_ID,CD_CODE
                    };
                    if (trbll.GetSourceTreeChild(caseTreeNodeRode["CD_ID"].ToString()).Rows.Count > 0)
                    {
                        node.Nodes.Add(new TreeNode());
                    }

                    Tree_Source.Nodes.Add(node);
                }
                #region 2017-11-2 ljj 解决基础数据部案例加工 增加的临时机制

                TreeNode nodeEx = new TreeNode
                {
                    Text = "裁判文书",//CD_Name,名称
                    Tag = "CD991106000000000,JudgeBook"//CD_ID,CD_CODE
                };
                nodeEx.Nodes.Add(new TreeNode());
                Tree_Source.Nodes.Add(nodeEx);
                #endregion
            }
        }

        /// <summary>
        /// 下级来源树
        /// </summary>
        /// <param name="parentNode">父节点</param>
        /// <param name="level">层级</param>
        private void BtnSourceTreeChild(TreeNode parentNode, int level)
        {
            TreeDataBLL trbll = new TreeDataBLL();
            var strArray = parentNode.Tag.ToString().Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);//ID,Code
            string pid = strArray[0];
            //DataTable caseTreeNodeRode = trbll.GetSourceTree(pid); //注释掉，不用ArgumentType和Argument表
            #region 2017-11-2 ljj 解决基础数据部案例加工 增加的临时机制
            if (pid == "CD991106000000000")// pid = "CD1709181032010818";//67 CD1609121111100001 160民事CD1709181032010818
            {
                DataTable dt = caseTypeDocTypeRelationBll.GetList();
                if (dt != null && dt.Rows.Count > 0)
                {
                    foreach (DataRow dr in dt.Rows)
                    {
                        TreeNode node = new TreeNode();
                        node.Text = LdFormat.ObjectToString(dr["LCR_Name"].ToString());
                        node.Tag = dr["LCR_ID"] + "," + dr["CD_Code"];
                        if (sysCaseTypeDocTypeParagBll.GetSysCaseTypeDocType(dr["CD_Code"].ToString(), "1").Rows.Count > 0)
                        {
                            node.Nodes.Add(new TreeNode());
                        }
                        parentNode.Nodes.Add(node);
                    }
                }
            }
            else if (parentNode.FullPath.StartsWith("裁判文书"))
            {
                if (level == 1)
                {
                    pid = strArray[1];
                }
                DataTable dt = sysCaseTypeDocTypeParagBll.GetSysCaseTypeDocType(pid, level.ToString());
                if (dt != null && dt.Rows.Count > 0)
                {
                    foreach (DataRow dr in dt.Rows)
                    {
                        TreeNode node = new TreeNode();
                        node.Text = LdFormat.ObjectToString(dr["CDL_Name"].ToString());
                        node.Tag = dr["CDL_ID"] + "," + dr["CDL_Code"];
                        if (sysCaseTypeDocTypeParagBll.GetSysCaseTypeDocType(dr["CDL_ID"].ToString(), (level + 1).ToString()).Rows.Count > 0)
                        {
                            node.Nodes.Add(new TreeNode());
                        }
                        parentNode.Nodes.Add(node);
                    }
                }
            }
            else
            {
                #endregion
                DataTable caseTreeNodeRode = trbll.GetSourceTreeChild(pid, level + 1);
                if (caseTreeNodeRode.Rows.Count == 0)
                    return;
                for (int i = 0; i < caseTreeNodeRode.Rows.Count; i++)
                {
                    TreeNode node = new TreeNode();
                    //node.Text = LdFormat.ObjectToString(caseTreeNodeRode.Rows[i]["name"]);
                    //node.Tag = caseTreeNodeRode.Rows[i]["id"];

                    node.Text = LdFormat.ObjectToString(caseTreeNodeRode.Rows[i]["CDL_Name"]);
                    node.Tag = caseTreeNodeRode.Rows[i]["CDL_ID"] + "," + caseTreeNodeRode.Rows[i]["CDL_Code"];//ID,Code

                    if (trbll.GetSourceTreeChild(LdFormat.ObjectToString(caseTreeNodeRode.Rows[i]["CDL_ID"]), level + 2).Rows.Count > 0)
                    {
                        node.Nodes.Add(new TreeNode());
                    }
                    parentNode.Nodes.Add(node);
                }
            }
        }

        /// <summary>
        /// 树展开
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Tree_Source_AfterExpand(object sender, TreeViewEventArgs e)
        {
            e.Node.Nodes.Clear();
            //加载下级树
            BtnSourceTreeChild(e.Node, e.Node.Level);
        }

        /// <summary>
        /// 加载批量选择节点类型列表
        /// </summary>
        /// <param name="ccId">情形情节节点ID</param>
        private void LoadCaseCouseListItem(string ccId)
        {
            CaseCauseBLL casecausebLl = new CaseCauseBLL();
            ddbChkType.Items.Clear();
            //获取节点类型列表
            var list = casecausebLl.GetCaseCauseTypeByCCId(ccId);
            if (list != null && list.Any())
            {
                ComboxItem[] comboxItems = list.Select(x => new ComboxItem(x.CcNodeTypeName, x.CcNodeType.ToString())).ToArray();
                ddbChkType.Items.AddRange(comboxItems);

                ddbChkType.Text = "请选择";
            }
            else
            {
                rbtnAddBatch.Enabled = false;
            }
        }

        /// <summary>
        /// 加载批量选择节点类型列表
        /// </summary>
        /// <param name="ccId">情形情节节点ID</param>
        private void LoadCaseCouseListItem1(string ccId)
        {
            SYS_InfoElementsBLL trbll = new SYS_InfoElementsBLL();
            ddbChkType.Items.Clear();
            //获取节点类型列表
            var list = trbll.GetInfoElementsTypeByEICId(ccId);
            if (list != null && list.Any())
            {
                ComboxItem[] comboxItems = list.Select(x => new ComboxItem(x.AM_Name, x.AM_Code.ToString())).ToArray();
                ddbChkType.Items.AddRange(comboxItems);

                ddbChkType.Text = "请选择";
            }
            else
            {
                rbtnAddBatch.Enabled = false;
            }
        }

        /// <summary>
        /// 单一选择
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void rbtnAddOne_CheckedChanged(object sender, EventArgs e)
        {

            ddbChkType.Enabled = false;
        }

        /// <summary>
        /// 批量选择
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void rbtnAddBatch_CheckedChanged(object sender, EventArgs e)
        {
            ddbChkType.Enabled = true;
        }

        /// <summary>
        /// 新建信息单元选择项事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void rbtnInfoNew_CheckedChanged(object sender, EventArgs e)
        {
            if (rbtnInfoNew.Checked)
            {
                lstBox.Enabled = false;
                lstBox.DataSource = null;
                //绑定数据列表
                //   BinddgvFrmInfoUnitData();

            }
        }

        /// <summary>
        /// 共用信息单元选择项事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void rbtnInfoCopy_CheckedChanged(object sender, EventArgs e)
        {
            if (rbtnInfoCopy.Checked)
            {
                lstBox.Enabled = true;
                LoadRegRelation(ClickNode.Tag.ToString());
            }
        }

        /// <summary>
        /// 获取信息来源（绑定的该节点已经建立的信息单元）
        /// </summary>
        /// <param name="ccId">情形情节ID</param>
        private void LoadRegRelation(string ccId)
        {
            AboutRegexBLL regexbll = new AboutRegexBLL();
            //信息来源（绑定的该节点已经建立的信息单元）
            var dt = regexbll.Relation_GetReg_EI_Code_Sql(ccId);//设置数据源
            if (dt != null && dt.Rows.Count > 0)
            {
                lstBox.DataSource = dt;
                lstBox.DisplayMember = "InfoName";//设置显示列
                lstBox.ValueMember = "CC_RegexInfoCode";//设置实际值
                lstBox.SelectedItems.Clear();
            }
            else
            {
                MsgBox.Warn("没有可用的信息单元！");
                rbtnInfoNew.Checked = true;
            }
        }

        /// <summary>
        /// 保存默认配置信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnConfirm_Click(object sender, EventArgs e)
        {
            DataRow[] ddrr = sysExpressSourceTable.Select(" EI_Name <> '机器学习' and CC_RegexInfoCode=''  ");
            if (ddrr.Length > 0)
            {
                MsgBox.Err("有未添加信息单元的来源规则！");
                return;
            }
            if (sysExpressSourceTable == null || sysExpressSourceTable.Rows.Count == 0)
            {
                MsgBox.Err("请设置来源规则后再试！");
                return;
            }
            //定义全局信息提示
            string msg = string.Empty;
            string msg_exist = string.Empty;
            var iSuccess = 0;
            var iFail = 0;
            if (rbtnAddOne.Checked)
            {
                if (sysExpressSourceTable != null && sysExpressSourceTable.Rows.Count > 0)
                {
                    for (int i = 0; i < sysExpressSourceTable.Rows.Count; i++)
                    {
                        SysExpressSource model = new SysExpressSource
                        {
                            ES_ID = sysExpressSourceTable.Rows[i]["ES_ID"].ToString(),
                            CC_ID = sysExpressSourceTable.Rows[i]["CC_ID"].ToString(),
                            Source_ID = sysExpressSourceTable.Rows[i]["Source_ID"].ToString(),
                            Source_Name = sysExpressSourceTable.Rows[i]["Source_Name"].ToString(),
                            Source_ParagraphID = sysExpressSourceTable.Rows[i]["Source_ParagraphID"].ToString(),
                            Source_ParagraphName = sysExpressSourceTable.Rows[i]["Source_ParagraphName"].ToString(),
                            EsPurposeId = sysExpressSourceTable.Rows[i]["ES_Purpose"].ToString(),
                            Source_TextType = sysExpressSourceTable.Rows[i]["Source_TextType"].ToString(),
                            EsPurposeName = sysExpressSourceTable.Rows[i]["ES_PurposeName"].ToString(),
                            CC_RegexInfoCode = sysExpressSourceTable.Rows[i]["CC_RegexInfoCode"].ToString(),
                            EIName = sysExpressSourceTable.Rows[i]["EI_Name"].ToString(),
                            IsML= Convert.ToInt32(sysExpressSourceTable.Rows[i]["IsML"])
                        };
                        if (!SourceBLL.Exists(model.CC_ID, model.Source_ID, model.Source_ParagraphID, model.Source_TextType, model.EsPurposeId))
                        {
                            if (SourceBLL.AddSource(model))
                            {
                                iSuccess++;
                            }
                            else
                            {
                                iFail++;
                            }

                        }
                        else
                        {
                            //msg_exist += string.Format("{0},用途为{1}的规则已存在\r\n", model.Source_Name + "-" + model.Source_ParagraphName, model.EsPurposeName);
                            //iFail++;
                        }
                    }
                    MsgBox.OK(string.Format("添加成功{0}条。\r\n失败{1}条。\r\n{2}", iSuccess, iFail, msg_exist.TrimEnd(',')));
                    this.Close();
                }
            }
            else if (rbtnAddBatch.Checked)
            {
                if (ddbChkType.Text == "请选择")
                {
                    MsgBox.Warn("请选择批量添加的节点类型");
                    return;
                }
                var dialogResult = MsgBox.Ask("批量添加，即为当前节点及所有子节点或属性添加所选择的来源，确认操作？");
                if (dialogResult == DialogResult.Yes)
                {

                    DataTable sysExpressSourceBatchTable = sysExpressSourceTable.Clone();
                    DataTable caseCausedt = new DataTable();
                    if (CCNodeType.Contains("t"))
                    {
                        var ccNodeTypes = ddbChkType.CheckBoxItems.Where(x => x.CheckState == CheckState.Checked).Select(x => ((ComboxItem)x.ComboBoxItem).Value).ToList();
                        caseCausedt = trbll.GetInfoElementsBatchSource(ClickNode.Tag.ToString(), ccNodeTypes, true);
                        if (caseCausedt != null && caseCausedt.Rows.Count > 0 && sysExpressSourceTable.Rows.Count > 0) //return new JsonMsg(true, "子节点为空", null);
                        {
                            for (int i = 0; i < caseCausedt.Rows.Count; i++)
                            {
                                string ccId = caseCausedt.Rows[i]["EIC_ID"].ToString();
                                for (int j = 0; j < sysExpressSourceTable.Rows.Count; j++)
                                {
                                    DataRow dr = sysExpressSourceBatchTable.NewRow();
                                    dr["ES_ID"] = newid.JudgeDoc_CreateID("SYS_Express_Source");
                                    dr["CC_ID"] = caseCausedt.Rows[i]["EIC_ID"].ToString();
                                    dr["Source_ID"] = sysExpressSourceTable.Rows[j]["Source_ID"].ToString();
                                    dr["Source_ParagraphID"] = sysExpressSourceTable.Rows[j]["Source_ParagraphID"].ToString();
                                    dr["Source_Name"] = sysExpressSourceTable.Rows[j]["Source_Name"].ToString();
                                    dr["Source_ParagraphName"] = sysExpressSourceTable.Rows[j]["Source_ParagraphName"].ToString();
                                    dr["EI_Name"] = sysExpressSourceTable.Rows[j]["EI_Name"].ToString();
                                    dr["ES_Purpose"] = sysExpressSourceTable.Rows[j]["ES_Purpose"].ToString();
                                    dr["Source_TextType"] = sysExpressSourceTable.Rows[j]["Source_TextType"].ToString();
                                    dr["ES_PurposeName"] = sysExpressSourceTable.Rows[j]["ES_PurposeName"].ToString();
                                    dr["Source_TextTypeName"] = sysExpressSourceTable.Rows[j]["Source_TextTypeName"].ToString();
                                    dr["IsML"] = sysExpressSourceTable.Rows[j]["IsML"].ToString();
                                    if (sysExpressSourceTable.Rows[j]["EI_Name"].ToString() == "新增")
                                    {
                                        #region  信息单元
                                        Reg_InfoUnit nodeChild = new Reg_InfoUnit();
                                        nodeChild.EI_Name = caseCausedt.Rows[i]["EIC_Name"].ToString();
                                        nodeChild.EN_ID = "EI_ID1507221438500001";
                                        nodeChild.EI_Remark = "";
                                        nodeChild.EI_ID = newid.CreateID("Reg_InfoUnit");
                                        nodeChild.EI_Code = nodeChild.EI_ID;//编号==ID 
                                        regexbll.AddReg_InfoUnit(nodeChild);
                                        //ccRegexInfoCode = nodeChild.EI_Code;
                                        #endregion
                                        dr["CC_RegexInfoCode"] = nodeChild.EI_Code;

                                    }
                                    else if (sysExpressSourceTable.Rows[j]["EI_Name"].ToString() == "新增(批量)")
                                    {
                                        if (dr["CC_ID"].ToString() == ClickNode.Tag.ToString())
                                        {
                                            dr["CC_RegexInfoCode"] = sysExpressSourceTable.Rows[j]["CC_RegexInfoCode"].ToString();
                                        }
                                        if (sysExpressSourceBatchTable.Select("CC_ID='" + caseCausedt.Rows[i]["EIC_ID"].ToString() + "'").Length > 0)
                                        {
                                            dr["CC_RegexInfoCode"] = sysExpressSourceBatchTable.Select("CC_ID='" + caseCausedt.Rows[i]["CC_ID"].ToString() + "'")[0]["CC_RegexInfoCode"].ToString();
                                        }
                                        else if (!SourceBLL.Exists(dr["CC_ID"].ToString(), dr["Source_ID"].ToString(), dr["Source_ParagraphID"].ToString(), dr["Source_TextType"].ToString(), dr["ES_Purpose"].ToString()))
                                        {
                                            #region  信息单元
                                            Reg_InfoUnit nodeChild = new Reg_InfoUnit();
                                            nodeChild.EI_Name = caseCausedt.Rows[i]["EIC_Name"].ToString();
                                            nodeChild.EN_ID = "EI_ID1507221438500001";
                                            nodeChild.EI_Remark = "";
                                            nodeChild.EI_ID = newid.CreateID("Reg_InfoUnit");
                                            nodeChild.EI_Code = nodeChild.EI_ID;//编号==ID 
                                            regexbll.AddReg_InfoUnit(nodeChild);
                                            //ccRegexInfoCode = nodeChild.EI_Code;
                                            #endregion
                                            dr["CC_RegexInfoCode"] = nodeChild.EI_Code;

                                        }

                                    }
                                    else
                                    {
                                        if (dr["CC_ID"].ToString() == ClickNode.Tag.ToString())
                                        {
                                            dr["CC_RegexInfoCode"] = sysExpressSourceTable.Rows[j]["CC_RegexInfoCode"].ToString();
                                        }
                                        else
                                        {
                                            var dt = regexbll.Relation_GetReg_EI_Code_Sql(dr["CC_ID"].ToString());
                                            //民事起诉书 - 起诉书首部(用途: 原告xml提取; 版本: 普通版本)
                                            string obj = sysExpressSourceTable.Rows[j]["EI_Name"].ToString();
                                            if (dt.Rows.Count > 0 && dt.Select("InfoName='" + obj + "'").Length > 0)
                                            {
                                                dr["CC_RegexInfoCode"] = dt.Select("InfoName='" + obj + "'")[0]["CC_RegexInfoCode"].ToString();
                                            }
                                        }
                                    }

                                    sysExpressSourceBatchTable.Rows.Add(dr);
                                }
                            }
                            // dgvFrmInfoUnit.DataSource = sysExpressSourceBatchTable;
                            #region 批量添加到数据库先注释
                            StringBuilder msgCCID = new StringBuilder();
                            msgCCID.Append("以下节点没有选择的共用信息单元：");
                            for (int i = 0; i < sysExpressSourceBatchTable.Rows.Count; i++)
                            {
                                SysExpressSource model = new SysExpressSource
                                {
                                    ES_ID = sysExpressSourceBatchTable.Rows[i]["ES_ID"].ToString(),
                                    CC_ID = sysExpressSourceBatchTable.Rows[i]["CC_ID"].ToString(),
                                    Source_ID = sysExpressSourceBatchTable.Rows[i]["Source_ID"].ToString(),
                                    Source_Name = sysExpressSourceBatchTable.Rows[i]["Source_Name"].ToString(),
                                    Source_ParagraphID = sysExpressSourceBatchTable.Rows[i]["Source_ParagraphID"].ToString(),
                                    Source_ParagraphName = sysExpressSourceBatchTable.Rows[i]["Source_ParagraphName"].ToString(),
                                    EsPurposeId = sysExpressSourceBatchTable.Rows[i]["ES_Purpose"].ToString(),
                                    Source_TextType = sysExpressSourceBatchTable.Rows[i]["Source_TextType"].ToString(),
                                    EsPurposeName = sysExpressSourceBatchTable.Rows[i]["ES_PurposeName"].ToString(),
                                    CC_RegexInfoCode = sysExpressSourceBatchTable.Rows[i]["CC_RegexInfoCode"].ToString(),
                                    EIName = sysExpressSourceBatchTable.Rows[i]["EI_Name"].ToString(),
                                    IsML =Convert.ToInt32(sysExpressSourceBatchTable.Rows[i]["IsML"].ToString())

                            };
                                if (!SourceBLL.Exists(model.CC_ID, model.Source_ID, model.Source_ParagraphID, model.Source_TextType, model.EsPurposeId))
                                {
                                    if (!string.IsNullOrEmpty(model.CC_RegexInfoCode))
                                    {
                                        if (SourceBLL.AddSource(model))
                                        {
                                            iSuccess++;
                                        }
                                        else
                                        {
                                            iFail++;
                                        }
                                    }
                                    else
                                    {
                                        iFail++;
                                        msgCCID.Append(model.CC_ID + ", ");

                                    }

                                }
                                else
                                {
                                    //msg_exist += string.Format("{0},用途为{1}的规则已存在\r\n", model.Source_Name + "-" + model.Source_ParagraphName, model.EsPurposeName);
                                    //iFail++;
                                }
                            }
                            MsgBox.OK(string.Format("总计{0}条。\r\n添加成功{1}条。\r\n失败{2}条。\r\n{3}", sysExpressSourceBatchTable.Rows.Count, iSuccess, iFail, msgCCID.ToString().TrimEnd(',')));
                            #endregion
                        }
                    }
                    else
                    {
                        var ccNodeTypes = ddbChkType.CheckBoxItems.Where(x => x.CheckState == CheckState.Checked).Select(x => int.Parse(((ComboxItem)x.ComboBoxItem).Value)).ToList();
                        caseCausedt = expressgroupsituationbll.GetCaseCauseBatchSource(ClickNode.Tag.ToString(), ccNodeTypes, true);
                        if (caseCausedt != null && caseCausedt.Rows.Count > 0 && sysExpressSourceTable.Rows.Count > 0) //return new JsonMsg(true, "子节点为空", null);
                        {
                            for (int i = 0; i < caseCausedt.Rows.Count; i++)
                            {
                                string ccId = caseCausedt.Rows[i]["CC_ID"].ToString();
                                for (int j = 0; j < sysExpressSourceTable.Rows.Count; j++)
                                {
                                    DataRow dr = sysExpressSourceBatchTable.NewRow();
                                    dr["ES_ID"] = newid.JudgeDoc_CreateID("SYS_Express_Source");
                                    dr["CC_ID"] = caseCausedt.Rows[i]["CC_ID"].ToString();
                                    dr["Source_ID"] = sysExpressSourceTable.Rows[j]["Source_ID"].ToString();
                                    dr["Source_ParagraphID"] = sysExpressSourceTable.Rows[j]["Source_ParagraphID"].ToString();
                                    dr["Source_Name"] = sysExpressSourceTable.Rows[j]["Source_Name"].ToString();
                                    dr["Source_ParagraphName"] = sysExpressSourceTable.Rows[j]["Source_ParagraphName"].ToString();
                                    dr["EI_Name"] = sysExpressSourceTable.Rows[j]["EI_Name"].ToString();
                                    dr["ES_Purpose"] = sysExpressSourceTable.Rows[j]["ES_Purpose"].ToString();
                                    dr["Source_TextType"] = sysExpressSourceTable.Rows[j]["Source_TextType"].ToString();
                                    dr["ES_PurposeName"] = sysExpressSourceTable.Rows[j]["ES_PurposeName"].ToString();
                                    dr["Source_TextTypeName"] = sysExpressSourceTable.Rows[j]["Source_TextTypeName"].ToString();
                                    dr["IsML"] = sysExpressSourceTable.Rows[j]["IsML"].ToString();
                                    if (sysExpressSourceTable.Rows[j]["EI_Name"].ToString() == "新增")
                                    {
                                        #region  信息单元
                                        Reg_InfoUnit nodeChild = new Reg_InfoUnit();
                                        nodeChild.EI_Name = caseCausedt.Rows[i]["CC_Name"].ToString();
                                        nodeChild.EN_ID = "EI_ID1507221438500001";
                                        nodeChild.EI_Remark = "";
                                        nodeChild.EI_ID = newid.CreateID("Reg_InfoUnit");
                                        nodeChild.EI_Code = nodeChild.EI_ID;//编号==ID 
                                        regexbll.AddReg_InfoUnit(nodeChild);
                                        //ccRegexInfoCode = nodeChild.EI_Code;
                                        #endregion
                                        dr["CC_RegexInfoCode"] = nodeChild.EI_Code;

                                    }
                                    else if (sysExpressSourceTable.Rows[j]["EI_Name"].ToString() == "新增(批量)")
                                    {
                                        if (dr["CC_ID"].ToString() == ClickNode.Tag.ToString())
                                        {
                                            dr["CC_RegexInfoCode"] = sysExpressSourceTable.Rows[j]["CC_RegexInfoCode"].ToString();
                                        }
                                        if (sysExpressSourceBatchTable.Select("CC_ID='" + caseCausedt.Rows[i]["CC_ID"].ToString() + "'").Length > 0)
                                        {
                                            dr["CC_RegexInfoCode"] = sysExpressSourceBatchTable.Select("CC_ID='" + caseCausedt.Rows[i]["CC_ID"].ToString() + "'")[0]["CC_RegexInfoCode"].ToString();
                                        }
                                        else if (!SourceBLL.Exists(dr["CC_ID"].ToString(), dr["Source_ID"].ToString(), dr["Source_ParagraphID"].ToString(), dr["Source_TextType"].ToString(), dr["ES_Purpose"].ToString()))
                                        {
                                            #region  信息单元
                                            Reg_InfoUnit nodeChild = new Reg_InfoUnit();
                                            nodeChild.EI_Name = caseCausedt.Rows[i]["CC_Name"].ToString();
                                            nodeChild.EN_ID = "EI_ID1507221438500001";
                                            nodeChild.EI_Remark = "";
                                            nodeChild.EI_ID = newid.CreateID("Reg_InfoUnit");
                                            nodeChild.EI_Code = nodeChild.EI_ID;//编号==ID 
                                            regexbll.AddReg_InfoUnit(nodeChild);
                                            //ccRegexInfoCode = nodeChild.EI_Code;
                                            #endregion
                                            dr["CC_RegexInfoCode"] = nodeChild.EI_Code;

                                        }

                                    }
                                    else
                                    {
                                        if (dr["CC_ID"].ToString() == ClickNode.Tag.ToString())
                                        {
                                            dr["CC_RegexInfoCode"] = sysExpressSourceTable.Rows[j]["CC_RegexInfoCode"].ToString();
                                        }
                                        else
                                        {
                                            var dt = regexbll.Relation_GetReg_EI_Code_Sql(dr["CC_ID"].ToString());
                                            //民事起诉书 - 起诉书首部(用途: 原告xml提取; 版本: 普通版本)
                                            string obj = sysExpressSourceTable.Rows[j]["EI_Name"].ToString();
                                            if (dt.Rows.Count > 0 && dt.Select("InfoName='" + obj + "'").Length > 0)
                                            {
                                                dr["CC_RegexInfoCode"] = dt.Select("InfoName='" + obj + "'")[0]["CC_RegexInfoCode"].ToString();
                                            }
                                            else if (obj.StartsWith("起诉状"))
                                            {
                                                string obj1 = obj.Replace("起诉状", "民事起诉书");
                                                if (dt.Rows.Count > 0 && dt.Select("InfoName='" + obj1 + "'").Length > 0)
                                                {
                                                    dr["CC_RegexInfoCode"] = dt.Select("InfoName='" + obj1 + "'")[0]["CC_RegexInfoCode"].ToString();
                                                }
                                            }
                                        }
                                    }

                                    sysExpressSourceBatchTable.Rows.Add(dr);
                                }
                            }
                            // dgvFrmInfoUnit.DataSource = sysExpressSourceBatchTable;
                            #region 批量添加到数据库先注释
                            StringBuilder msgCCID = new StringBuilder();
                            msgCCID.Append("以下节点没有选择的共用信息单元：");
                            for (int i = 0; i < sysExpressSourceBatchTable.Rows.Count; i++)
                            {
                                SysExpressSource model = new SysExpressSource
                                {
                                    ES_ID = sysExpressSourceBatchTable.Rows[i]["ES_ID"].ToString(),
                                    CC_ID = sysExpressSourceBatchTable.Rows[i]["CC_ID"].ToString(),
                                    Source_ID = sysExpressSourceBatchTable.Rows[i]["Source_ID"].ToString(),
                                    Source_Name = sysExpressSourceBatchTable.Rows[i]["Source_Name"].ToString(),
                                    Source_ParagraphID = sysExpressSourceBatchTable.Rows[i]["Source_ParagraphID"].ToString(),
                                    Source_ParagraphName = sysExpressSourceBatchTable.Rows[i]["Source_ParagraphName"].ToString(),
                                    EsPurposeId = sysExpressSourceBatchTable.Rows[i]["ES_Purpose"].ToString(),
                                    Source_TextType = sysExpressSourceBatchTable.Rows[i]["Source_TextType"].ToString(),
                                    EsPurposeName = sysExpressSourceBatchTable.Rows[i]["ES_PurposeName"].ToString(),
                                    CC_RegexInfoCode = sysExpressSourceBatchTable.Rows[i]["CC_RegexInfoCode"].ToString(),
                                    EIName = sysExpressSourceBatchTable.Rows[i]["EI_Name"].ToString(),
                                    IsML =Convert.ToInt32(sysExpressSourceBatchTable.Rows[i]["IsML"].ToString())
                            };
                                if (!SourceBLL.Exists(model.CC_ID, model.Source_ID, model.Source_ParagraphID, model.Source_TextType, model.EsPurposeId))
                                {
                                    if (!string.IsNullOrEmpty(model.CC_RegexInfoCode))
                                    {
                                        if (SourceBLL.AddSource(model))
                                        {
                                            iSuccess++;
                                        }
                                        else
                                        {
                                            iFail++;
                                        }
                                    }
                                    else
                                    {
                                        iFail++;
                                        msgCCID.Append(model.CC_ID + ", ");

                                    }

                                }
                                else
                                {
                                    //msg_exist += string.Format("{0},用途为{1}的规则已存在\r\n", model.Source_Name + "-" + model.Source_ParagraphName, model.EsPurposeName);
                                    //iFail++;
                                }
                            }
                            MsgBox.OK(string.Format("总计{0}条。\r\n添加成功{1}条。\r\n失败{2}条。\r\n{3}", sysExpressSourceBatchTable.Rows.Count, iSuccess, iFail, msgCCID.ToString().TrimEnd(',')));
                            #endregion
                        }
                    }
                    // caseCausedt = caseCausedt.Select("CC_ID<>" + ClickNode.Tag.ToString()).CopyToDataTable();

                }
                else
                {
                    return;
                }
            }

        }

        #region 原来单一和 批量添加代码
        ///// <summary>
        ///// 单一添加
        ///// </summary>
        //public void AddOneSource()
        //{
        //    //定义全局信息提示
        //    string msg = string.Empty;
        //    string msg_exist = string.Empty;
        //    var iSuccess = 0;
        //    var iFail = 0;
        //    //var iExist = 0;

        //    NewIDBLL newid = new NewIDBLL();
        //    Express_SourceBLL SourceBLL = new Express_SourceBLL();
        //    AboutRegexBLL regexbll = new AboutRegexBLL();
        //    //获取需要复制的信息单元，如果没有，则默认是新建信息单元
        //    var ids = lstBox.DataSource != null ? ((DataRowView)lstBox.SelectedItem).Row.ItemArray[1].ToString() : string.Empty;
        //    var ccRegexInfoCode = rbtnInfoNew.Checked ? string.Empty : ids.Split('|')[0];

        //    foreach (TreeNode node in SourceNodeList)
        //    {
        //        if (node.Checked)
        //        {
        //            string parentid = "";
        //            string parentName = "";
        //            var strArray = new string[] { };
        //            var sourceParaId = string.Empty;

        //            if (node.Level == 1)
        //            {
        //                parentName = node.Parent.Text;
        //                strArray = node.Parent.Tag.ToString().Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);
        //                parentid = strArray[1];
        //            }
        //            else if (node.Level == 2)
        //            {
        //                parentName = node.Parent.Parent.Text;
        //                strArray = node.Parent.Parent.Tag.ToString().Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);
        //                parentid = strArray[1];
        //            }
        //            else
        //            {
        //                parentName = node.Text;
        //                strArray = node.Tag.ToString().Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);
        //                parentid = strArray[1];
        //            }

        //            sourceParaId =
        //                node.Tag.ToString().Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries)[1];
        //            //if (node.Parent != null)
        //            //{
        //            //    parentName = node.Parent.Text;
        //            //    parentid = node.Parent.Tag.ToString();
        //            //}
        //            //else
        //            //{
        //            //    parentName = node.Text;
        //            //    parentid = node.Tag.ToString();
        //            //}
        //            //定义方法委托，获取版本列表
        //            var selectVersionList = new List<DataRow>();
        //            Action versionMethod = null;
        //            versionMethod = () =>
        //            {
        //                for (int i = 0; i < this.chkListBox_Version1.Items.Count; i++)
        //                {
        //                    if (chkListBox_Version1.GetItemChecked(i))
        //                    {
        //                        selectVersionList.Add(((DataRowView)chkListBox_Version1.Items[i]).Row);
        //                    }
        //                }

        //            };
        //            //执行方法
        //            versionMethod();
        //            //定义方法委托，获取用途列表
        //            var selectPurposeList = new List<DataRow>();
        //            Action purposeMethod = null;
        //            purposeMethod = () =>
        //            {
        //                for (int i = 0; i < chkLstBox_Purpose1.Items.Count; i++)
        //                {
        //                    if (chkLstBox_Purpose1.GetItemChecked(i))
        //                    {
        //                        selectPurposeList.Add(((DataRowView)chkLstBox_Purpose1.Items[i]).Row);
        //                    }
        //                }

        //            };
        //            //执行方法
        //            purposeMethod();
        //            //循环版本，添加信息来源
        //            foreach (DataRow versionItem in selectVersionList)
        //            {
        //                //循环用途，添加信息来源
        //                foreach (DataRow purposeItem in selectPurposeList)
        //                {
        //                    if (!SourceBLL.Exists(ClickNode.Tag.ToString(), parentid, sourceParaId, versionItem["AM_Code"].ToString(), purposeItem.ItemArray[0].ToString())) //不存在
        //                    {
        //                        SysExpressSource model = new SysExpressSource
        //                        {
        //                            ES_ID = newid.JudgeDoc_CreateID("SYS_Express_Source"),
        //                            CC_ID = ClickNode.Tag.ToString(),
        //                            Source_ID = parentid,
        //                            Source_Name = parentName,
        //                            Source_ParagraphID = sourceParaId,
        //                            Source_ParagraphName = node.Text,
        //                            EsPurposeId = purposeItem.ItemArray[0].ToString(),
        //                            Source_TextType = versionItem["AM_Code"].ToString()
        //                        };
        //                        //model.Source_ParagraphID = node.Tag.ToString();

        //                        //正则不为空，则不需要添加信息来源，这里可以理解为为同一个节点添加信息来源，信息来源是一样的 todo by zhangpeng
        //                        if (string.IsNullOrEmpty(ccRegexInfoCode))
        //                        {
        //                            #region  信息单元
        //                            Reg_InfoUnit nodeChild = new Reg_InfoUnit();
        //                            nodeChild.EI_Name = ClickNode.Text;
        //                            nodeChild.EN_ID = "EI_ID1507221438500001";
        //                            nodeChild.EI_Remark = "";
        //                            nodeChild.EI_ID = newid.CreateID("Reg_InfoUnit");
        //                            nodeChild.EI_Code = nodeChild.EI_ID;//编号==ID 
        //                            regexbll.AddReg_InfoUnit(nodeChild);
        //                            ccRegexInfoCode = nodeChild.EI_Code;
        //                            #endregion
        //                        }
        //                        model.CC_RegexInfoCode = ccRegexInfoCode;
        //                        if (SourceBLL.AddSource(model))
        //                        {
        //                            //MsgBox.OK("添加成功!");
        //                            iSuccess++;
        //                        }
        //                        else
        //                        {
        //                            //MsgBox.Err("添加失败!");
        //                            iFail++;
        //                        }

        //                    }
        //                    else
        //                    {

        //                        //MsgBox.Warn("当前规则已存在!");
        //                        msg_exist += string.Format("{0},用途为{1}的规则已存在\r\n", parentName + "-" + node.Text, purposeItem.ItemArray[2]);
        //                        iFail++;
        //                    }
        //                }
        //            }
        //        }
        //    }

        //    MsgBox.OK(string.Format("添加成功{0}条。\r\n失败{1}条。\r\n{2}", iSuccess, iFail, msg_exist.TrimEnd(',')));

        //    //Sourceframe.Visible = false;
        //    rbtnInfoNew.Checked = true;
        //    //ShowSource(clicknode.Tag.ToString());
        //}

        ///// <summary>
        ///// 批量添加
        ///// </summary>
        //public void AddBatchSource()
        //{
        //    //定义全局信息提示
        //    string msg = string.Empty;
        //    string msg_exist = string.Empty;
        //    var iSuccess = 0;
        //    var iFail = 0;
        //    //var iExist = 0;

        //    NewIDBLL newid = new NewIDBLL();
        //    Express_SourceBLL SourceBLL = new Express_SourceBLL();
        //    AboutRegexBLL regexbll = new AboutRegexBLL();
        //    if (ddbChkType.Text == "请选择")
        //    {
        //        MsgBox.Warn("请选择批量添加的节点类型");
        //        return;
        //    }
        //    var ccNodeTypes = ddbChkType.CheckBoxItems.Where(x => x.CheckState == CheckState.Checked)
        //      .Select(x => int.Parse(((ComboxItem)x.ComboBoxItem).Value))
        //         .ToList();

        //    var dialogResult = MsgBox.Ask("批量添加，即为当前节点及所有子节点或属性添加所选择的来源，确认操作？");
        //    if (dialogResult == DialogResult.Yes)
        //    {
        //        //获取需要复制的信息单元，如果没有，则默认是新建信息单元
        //        var ids = lstBox.DataSource != null ? ((DataRowView)lstBox.SelectedItem).Row.ItemArray[1].ToString() : string.Empty;
        //        var ccRegexInfoCode = rbtnInfoNew.Checked ? string.Empty : ids.Split('|')[0];
        //        //以下三个属性，在批量添加中，需要传递到子节点中进行判断 todo by zhangpeng
        //        var copySourceId = rbtnInfoNew.Checked ? string.Empty : ids.Split('|')[1];
        //        var copySourceParagraphId = rbtnInfoNew.Checked ? string.Empty : ids.Split('|')[2];
        //        var copyEsPurposeId = rbtnInfoNew.Checked ? string.Empty : ids.Split('|')[3];
        //        var copySourceTextType = rbtnInfoNew.Checked ? string.Empty : ids.Split('|')[4];

        //        //添加所有选择的来源节点
        //        var sysExpressSources = new List<SysExpressSource>();

        //        foreach (TreeNode node in SourceNodeList)
        //        {
        //            //节点选择
        //            if (node.Checked)
        //            {
        //                string parentid = "";
        //                string parentName = "";
        //                var strArray = new string[] { };
        //                var sourceParaId = string.Empty;

        //                if (node.Level == 1)
        //                {
        //                    parentName = node.Parent.Text;
        //                    strArray = node.Parent.Tag.ToString().Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);
        //                    parentid = strArray[1];
        //                }
        //                else if (node.Level == 2)
        //                {
        //                    parentName = node.Parent.Parent.Text;
        //                    strArray = node.Parent.Parent.Tag.ToString().Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);
        //                    parentid = strArray[1];
        //                }
        //                else
        //                {
        //                    parentName = node.Text;
        //                    strArray = node.Tag.ToString().Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);
        //                    parentid = strArray[1];
        //                }

        //                sourceParaId =
        //                    node.Tag.ToString().Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries)[1];
        //                var selectVersionList = new List<DataRow>();
        //                Action versionMethod = null;
        //                versionMethod = () =>
        //                {
        //                    for (int i = 0; i < this.chkListBox_Version1.Items.Count; i++)
        //                    {
        //                        if (chkListBox_Version1.GetItemChecked(i))
        //                        {
        //                            selectVersionList.Add(((DataRowView)chkListBox_Version1.Items[i]).Row);
        //                        }
        //                    }

        //                };
        //                //执行方法
        //                versionMethod();
        //                //定义方法委托，获取用途列表
        //                var selectPurposeList = new List<DataRow>();
        //                Action purposeMethod = null;
        //                purposeMethod = () =>
        //                {
        //                    for (int i = 0; i < chkLstBox_Purpose1.Items.Count; i++)
        //                    {
        //                        if (chkLstBox_Purpose1.GetItemChecked(i))
        //                        {
        //                            selectPurposeList.Add(((DataRowView)chkLstBox_Purpose1.Items[i]).Row);
        //                        }
        //                    }

        //                };
        //                //执行方法
        //                purposeMethod();
        //                //循环版本，添加信息来源
        //                foreach (DataRow versionItem in selectVersionList)
        //                {
        //                    //循环用途，添加信息来源
        //                    foreach (DataRow purposeItem in selectPurposeList)
        //                    {
        //                        if (!SourceBLL.Exists(ClickNode.Tag.ToString(), parentid, sourceParaId, versionItem["AM_Code"].ToString(), purposeItem.ItemArray[0].ToString())) //不存在
        //                        {
        //                            SysExpressSource model = new SysExpressSource
        //                            {
        //                                ES_ID = newid.JudgeDoc_CreateID("SYS_Express_Source"),
        //                                CC_ID = ClickNode.Tag.ToString(),
        //                                Source_ID = parentid,
        //                                Source_Name = parentName,
        //                                Source_ParagraphID = sourceParaId,
        //                                //Source_ParagraphID = node.Tag.ToString(),
        //                                Source_ParagraphName = node.Text,
        //                                EsPurposeId = purposeItem.ItemArray[0].ToString(),
        //                                Source_TextType = versionItem["AM_Code"].ToString(),
        //                            };

        //                            //正则不为空，则不需要添加信息来源，这里可以理解为为同一个节点添加信息来源，信息来源是一样的 todo by zhangpeng
        //                            if (ccRegexInfoCode == "")
        //                            {
        //                                #region  信息单元
        //                                Reg_InfoUnit nodeChild = new Reg_InfoUnit();
        //                                nodeChild.EI_Name = ClickNode.Text;
        //                                nodeChild.EN_ID = "EI_ID1507221438500001";
        //                                nodeChild.EI_Remark = "";
        //                                nodeChild.EI_ID = newid.CreateID("Reg_InfoUnit");
        //                                nodeChild.EI_Code = nodeChild.EI_ID;//编号==ID 
        //                                regexbll.AddReg_InfoUnit(nodeChild);
        //                                ccRegexInfoCode = nodeChild.EI_Code;
        //                                #endregion
        //                            }
        //                            model.CC_RegexInfoCode = ccRegexInfoCode;
        //                            //添加节点
        //                            if (SourceBLL.AddSource(model))
        //                            {
        //                                iSuccess++;
        //                            }
        //                            else
        //                            {
        //                                iFail++;
        //                            }
        //                        }
        //                        else
        //                        {
        //                            //iExist++;
        //                            msg_exist += string.Format("{2}的{0}-用途为{1}的规则已存在\r\n", parentName + "-" + node.Text, purposeItem.ItemArray[2], ClickNode.Text);
        //                            iFail++;
        //                        }

        //                        //设置批量添加子节点的模型
        //                        var batchModel = new SysExpressSource()
        //                        {
        //                            CC_ID = ClickNode.Tag.ToString(),
        //                            Source_ID = parentid,
        //                            Source_Name = parentName,
        //                            //Source_ParagraphID = node.Tag.ToString(),
        //                            Source_ParagraphID = sourceParaId,
        //                            Source_ParagraphName = node.Text,
        //                            CC_RegexInfoCode = ccRegexInfoCode,
        //                            CopyEsPurposeId = copyEsPurposeId,
        //                            CopySourceId = copySourceId,
        //                            CopySourceParagraphId = copySourceParagraphId,
        //                            CopySourceTextType = copySourceTextType,
        //                            EsPurposeId = purposeItem.ItemArray[0].ToString(),
        //                            EsPurposeName = purposeItem.ItemArray[2].ToString(),
        //                            Source_TextType = versionItem["AM_Code"].ToString()
        //                        };
        //                        sysExpressSources.Add(batchModel);
        //                    }
        //                }
        //            }
        //        }
        //        //批量添加子节点和属性
        //        var jsonMsg = SourceBLL.BatchAddSource(ClickNode.Tag.ToString(), sysExpressSources, ccNodeTypes);
        //        if (jsonMsg.Result)
        //        {
        //            if (jsonMsg.Data != null)
        //            {
        //                var dic = (Dictionary<string, string>)jsonMsg.Data;
        //                iSuccess = iSuccess + int.Parse(dic["iSuccess"]);
        //                iFail = iFail + int.Parse(dic["iFail"]);
        //                msg_exist = msg_exist + dic["msg_exist"];
        //            }
        //        }
        //        else
        //        {
        //            if (jsonMsg.Data != null)
        //            {
        //                var dic = (Dictionary<string, string>)jsonMsg.Data;
        //                iSuccess = iSuccess + int.Parse(dic["iSuccess"]);
        //                iFail = iFail + int.Parse(dic["iFail"]);
        //                msg_exist = msg_exist + dic["msg_exist"];
        //            }

        //            msg = jsonMsg.Message;
        //            MsgBox.OK(string.Format(msg + "\r\n" + "添加成功{0}条，失败{1}条\r\n{2}", iSuccess, iFail, msg_exist.TrimEnd(',')));
        //            return;
        //        }
        //        //{
        //        //    //MsgBox.OK("批量添加成功");
        //        //    ////tran.Complete();
        //        //    //Sourceframe.Visible = false;
        //        //    //ShowSource(.Tag.ToString());
        //        //    iSuccess += sysExpressSources != null && sysExpressSources.Any() ? sysExpressSources.Count : 0;

        //        //}
        //        //else
        //        //{
        //        //    //MsgBox.Warn("批量添加失败！");
        //        //    iFail++;
        //        //}
        //    }
        //    MsgBox.OK(string.Format("添加成功{0}条，失败{1}条\r\n{2}", iSuccess, iFail, msg_exist.TrimEnd(',')));
        //    rbtnInfoNew.Checked = true;
        //} 
        #endregion

        #endregion

        /// <summary>
        /// 窗体关闭事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnClose_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.Yes;
        }
        #endregion

        #region 用途管理

        /// <summary>
        /// 加载用途字典信息
        /// </summary>
        private void LoadPurposeList()
        {
            ArgumentTypeXmlBLL bll = new ArgumentTypeXmlBLL();
            //获取用途类型下的字典列表
            var dt = bll.GetArgumentDtByType("Purpose");
            chkLstBox_Purpose.DataSource = dt;
            chkLstBox_Purpose.DisplayMember = "AM_Name";
            chkLstBox_Purpose.ValueMember = "AM_ID";
            chkLstBox_Purpose.SelectedIndex = -1;
        }

        /// <summary>
        /// 加载版本字典
        /// </summary>
        private void LoadVersionList()
        {
            ArgumentTypeXmlBLL bll = new ArgumentTypeXmlBLL();
            //获取用途类型下的字典列表
            var dt = bll.GetArgumentDtByType("TextType");
            chkListBox_Version.DataSource = dt;
            chkListBox_Version.DisplayMember = "AM_Name";
            chkListBox_Version.ValueMember = "AM_Code";
            chkListBox_Version.SelectedIndex = -1;
        }

        #region 未用编辑版本与用途按钮事件
        /// <summary>
        /// 编辑用途
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnEditPurpose_Click(object sender, EventArgs e)
        {
            var frm = frmDictEdit.Instance;
            frm.m_dictCode = "Purpose";
            var dialogResult = frm.ShowDialog(this);
            if (dialogResult == DialogResult.Cancel)
            {
                frm.Close();
                LoadPurposeList();
            }
            //ArgumentTypeXmlBLL bll = new ArgumentTypeXmlBLL();
            ////获取用途类型下的字典列表
            //var dt = bll.GetArgumentDtByType("Purpose");
            //lstPurposeManange.DataSource = dt;
            //lstPurposeManange.DisplayMember = "AM_Name";
            //lstPurposeManange.ValueMember = "AM_ID";

            //txtPurposeName.Text = string.Empty;
            //txtPurposeName.Tag = null;
            //pnlPurpose.Visible = true;
        }

        private void btnEditVersion_Click(object sender, EventArgs e)
        {
            var frm = frmDictEdit.Instance;
            frm.m_dictCode = "TextType";
            var dialogResult = frm.ShowDialog(this);
            if (dialogResult == DialogResult.Cancel)
            {
                frm.Close();
                LoadVersionList();
            }
        }

        /// <summary>
        /// 关闭版本管理
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button2_Click(object sender, EventArgs e)
        {
            //pnlVersion.Visible = false;
        }

        /// <summary>
        /// 删除用途名称
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnPurposeDel_Click(object sender, EventArgs e)
        {
            ////用途如果在信息来源中使用过，则无法删除，需要提示
            //var dialogResult = MsgBox.Ask("删除后无法恢复，确认继续操作？");
            //if (dialogResult == DialogResult.Yes)
            //{
            //    //判断sys_express_source表中是否已使用过该节点，如果使用，则提示无法删除
            //    Express_SourceBLL exBll = new Express_SourceBLL();
            //    if (exBll.ExistsByPurposeId(
            //        ((DataRowView)lstPurposeManange.Items[lstPurposeManange.Items.Count - 1]).Row.ItemArray[0].ToString()))
            //    {
            //        MsgBox.Warn("信息来源中已使用该用途，必须删除该信息来源后，才可以删除用途信息");
            //        return;
            //    }
            //    else
            //    {
            //        ArgumentTypeXmlBLL bll = new ArgumentTypeXmlBLL();
            //        if (bll.Delete(((DataRowView)lstPurposeManange.Items[lstPurposeManange.Items.Count - 1]).Row.ItemArray[0].ToString
            //            ()))
            //        {
            //            MsgBox.OK("删除成功");
            //            LoadPurposeList();
            //        }
            //    }


            //}

        }

        /// <summary>
        /// 单击用途列表选项时，触发
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void lstPurposeManange_Click(object sender, EventArgs e)
        {
            //var name = lstPurposeManange.GetItemText(lstPurposeManange.SelectedItem);
            //var value = ((DataRowView)lstPurposeManange.SelectedItem).Row.ItemArray[0];
            //txtPurposeName.Text = name;
            //txtPurposeName.Tag = value;
        }

        /// <summary>
        /// 用途保存
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnPurposeSave_Click(object sender, EventArgs e)
        {
            //if (string.IsNullOrEmpty(txtPurposeName.Text))
            //{
            //    MsgBox.Warn("用途名称不能为空");
            //    return;
            //}
            //else
            //{
            //    ArgumentTypeXmlBLL bll = new ArgumentTypeXmlBLL();
            //    //1.判断字典类型为用途的列表中是否存在相同名称的数据
            //    if (bll.IsExist(txtPurposeName.Text, "Purpose"))
            //    {
            //        MsgBox.Warn("用途名称已经存在，请重新添加");
            //        txtPurposeName.Focus();
            //        return;
            //    }
            //    else //2.不存在则可以保存
            //    {
            //        //3.判断新增或编辑的条件是txtPurposeName.Tag是否为空

            //        //todo by zhgangpeng,考虑到数据一致性，需要更新sys_express_source等表，暂时不做更新功能。
            //        if (txtPurposeName.Tag != null) //编辑
            //        {
            //            SYS_Argument model = new SYS_Argument()
            //            {
            //                AM_Name = txtPurposeName.Text,
            //                AM_ID = txtPurposeName.Tag.ToString()
            //            };
            //            bll.UpdateName(model);
            //        }
            //        else  //新增
            //        {
            //            SYS_Argument model = new SYS_Argument()
            //            {
            //                AM_Name = txtPurposeName.Text,
            //                AM_ID = Guid.NewGuid().ToString(),
            //                AM_ShowIndex = decimal.Parse(((DataRowView)lstPurposeManange.Items[lstPurposeManange.Items.Count - 1]).Row.ItemArray[5].ToString()) + 1,
            //                AM_Code = (decimal.Parse(((DataRowView)lstPurposeManange.Items[lstPurposeManange.Items.Count - 1]).Row.ItemArray[3].ToString()) + 1).ToString(),
            //                AT_ID = ((DataRowView)lstPurposeManange.Items[lstPurposeManange.Items.Count - 1]).Row.ItemArray[1].ToString()
            //            };
            //            if (bll.Add(model))
            //            {
            //                MsgBox.OK("添加成功");
            //                txtPurposeName.Text = string.Empty;
            //                LoadPurposeList();
            //            }
            //            else
            //            {
            //                MsgBox.OK("添加失败");
            //            }
            //        }
            //    }
            //}
        }
        /// <summary>
        /// 版本保存
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button3_Click(object sender, EventArgs e)
        {
            //if (string.IsNullOrEmpty(this.textVersionName.Text))
            //{
            //    MsgBox.Warn("版本名称不能为空");
            //    return;
            //}
            //else
            //{
            //    ArgumentTypeXmlBLL bll = new ArgumentTypeXmlBLL();
            //    //1.判断字典类型为用途的列表中是否存在相同名称的数据
            //    if (bll.IsExist(textVersionName.Text, "TextType"))
            //    {
            //        MsgBox.Warn("版本名称已经存在，请重新添加");
            //        textVersionName.Focus();
            //        return;
            //    }
            //    else //2.不存在则可以保存
            //    {
            //        //3.判断新增或编辑的条件是txtPurposeName.Tag是否为空

            //        //todo by zhgangpeng,考虑到数据一致性，需要更新sys_express_source等表，暂时不做更新功能。
            //        if (textVersionName.Tag != null) //编辑
            //        {
            //            SYS_Argument model = new SYS_Argument()
            //            {
            //                AM_Name = textVersionName.Text,
            //                AM_ID = textVersionName.Tag.ToString()
            //            };
            //            bll.UpdateName(model);
            //        }
            //        else  //新增
            //        {
            //            SYS_Argument model = new SYS_Argument()
            //            {
            //                AM_Name = textVersionName.Text,
            //                AM_ID = Guid.NewGuid().ToString(),
            //                AM_ShowIndex = decimal.Parse(((DataRowView)lstPurposeManange.Items[lstPurposeManange.Items.Count - 1]).Row.ItemArray[5].ToString()) + 1,
            //                AM_Code = (decimal.Parse(((DataRowView)lstPurposeManange.Items[lstPurposeManange.Items.Count - 1]).Row.ItemArray[3].ToString()) + 1).ToString(),
            //                AT_ID = ((DataRowView)lstPurposeManange.Items[lstPurposeManange.Items.Count - 1]).Row.ItemArray[1].ToString()
            //            };
            //            if (bll.Add(model))
            //            {
            //                MsgBox.OK("添加成功");
            //                txtPurposeName.Text = string.Empty;
            //                LoadPurposeList();
            //            }
            //            else
            //            {
            //                MsgBox.OK("添加失败");
            //            }
            //        }
            //    }
            //}
        }

        #endregion


        #endregion


        /// <summary>
        /// 窗体关闭
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void FrmInfoUnit_FormClosing(object sender, FormClosingEventArgs e)
        {
            DialogResult = DialogResult.Yes;
        }

        /// <summary>
        /// 启用默认选择后事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ckbInfoUnit_Click(object sender, EventArgs e)
        {
            if (ckbInfoUnit.Checked)
            {
                groupBox1.Enabled = false;
                Tree_Source.ForeColor = System.Drawing.Color.Gray;
                groupBox9.Enabled = false;
                clearInput();
                chkLstBox_Purpose.DataSource = sysExpressSourceDefaultTable;
                chkLstBox_Purpose.DisplayMember = "ES_PurposeName";
                chkLstBox_Purpose.ValueMember = "ES_PurposeID";
                chkLstBox_Purpose.SelectedIndex = -1;
            }
            else
            {
                LoadPurposeList();
            }
        }


        /// <summary>
        /// 绑定添加来源数据
        /// </summary>
        /// <param name="type">类型 默认是使用信息单元配置0 机器学习配置1</param>
        private void BinddgvFrmInfoUnitData(int type=0)
        {
            #region 判断来源及逻辑段和版本与用途是否选择正确
            //1.判断用途是否选择
            if (chkLstBox_Purpose.SelectedItems.Count <= 0)
            {
                MsgBox.Warn("请先选择规则用途");
                return;
            }
            //2.判断来源及逻辑树是否已选择
            if (Tree_Source.SelectedNode == null)
            {
                MsgBox.Warn("请先选择左边树节点");
                return;
            }
            //2.判断版本是否选择
            if (chkListBox_Version.SelectedItems.Count <= 0)
            {
                MsgBox.Warn("请先选择规则版本");
                return;
            }
            //信息单元配置
            if (type == 0)
            {
                if (!rbtnInfoNew.Checked && !rbtnInfoCopy.Checked)
                {
                    MsgBox.Warn("请先选择信息单元后再试！");
                    return;

                }
                if (rbtnInfoCopy.Checked && lstBox.SelectedItem == null)
                {
                    MsgBox.Warn("请选择公用信息单元后再试");
                    return;
                }
            }
            #endregion
            //从上面规则中添加来源列表信息
            string parentid;
            string parentName;
            string[] strArray;
            string sourceParaId;
            string sourceParagraphName;

            if (Tree_Source.SelectedNode.FullPath.StartsWith("裁判文书"))
            {
                string[] res = Tree_Source.SelectedNode.FullPath.Replace("裁判文书\\", "").Split(new string[] { "\\" }, StringSplitOptions.RemoveEmptyEntries);
                TreeNode tn = FindNodeByText(FindParentNode(Tree_Source.SelectedNode), res[0].Trim());
                parentName = tn.Text;
                strArray = tn.Tag.ToString().Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);
                parentid = strArray[1];
            }
            else
            {
                string[] res = Tree_Source.SelectedNode.FullPath.Split(new string[] { "\\" }, StringSplitOptions.RemoveEmptyEntries);
                TreeNode tn = FindNodeByText(FindParentNode(Tree_Source.SelectedNode), res[0].Trim());
                parentName = tn.Text;
                strArray = tn.Tag.ToString().Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);
                parentid = strArray[1];
            }           

            sourceParaId =
                Tree_Source.SelectedNode.Tag.ToString().Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries)[1];
            sourceParagraphName = Tree_Source.SelectedNode.Text;

            DataRow dr = sysExpressSourceTable.NewRow();
            dr["ES_ID"] = newid.JudgeDoc_CreateID("SYS_Express_Source");
            dr["CC_ID"] = ClickNode.Tag.ToString();
            dr["Source_ID"] = parentid;
            dr["Source_ParagraphID"] = sourceParaId;
            dr["Source_Name"] = parentName;
            dr["Source_ParagraphName"] = sourceParagraphName;
            string ccRegexInfoCode=string.Empty;
            if (type == 0)
            {
                ccRegexInfoCode = lstBox.DataSource != null ? ((DataRowView)lstBox.SelectedItem).Row[0].ToString() : string.Empty;
                if (string.IsNullOrEmpty(ccRegexInfoCode))
                {
                    #region  信息单元
                    Reg_InfoUnit nodeChild = new Reg_InfoUnit();
                    nodeChild.EI_Name = ClickNode.Text;
                    nodeChild.EN_ID = "EI_ID1507221438500001";
                    nodeChild.EI_Remark = "";
                    nodeChild.EI_ID = newid.CreateID("Reg_InfoUnit");
                    nodeChild.EI_Code = nodeChild.EI_ID;//编号==ID 
                    regexbll.AddReg_InfoUnit(nodeChild);
                    ccRegexInfoCode = nodeChild.EI_Code;
                    #endregion
                }
            }
            else
            {
                Reg_InfoUnit nodeChild = new Reg_InfoUnit();
                nodeChild.EI_Name = ClickNode.Text;
                nodeChild.EN_ID = "";
                nodeChild.EI_Remark = "";
                nodeChild.EI_ID = newid.CreateID("Reg_InfoUnit");
                nodeChild.EI_Code = nodeChild.EI_ID;//编号==ID 
                regexbll.AddReg_InfoUnit(nodeChild);
                ccRegexInfoCode = nodeChild.EI_Code;
            }
            dr["CC_RegexInfoCode"] = ccRegexInfoCode;
            dr["ES_Purpose"] = ((DataRowView)this.chkLstBox_Purpose.SelectedItem).Row[0].ToString();
            dr["Source_TextType"] = ((DataRowView)this.chkListBox_Version.SelectedItem).Row[2].ToString();
            dr["EI_Name"] = type==1? "机器学习": rbtnInfoNew.Checked ? "新增" : lstBox.DataSource != null ? ((DataRowView)lstBox.SelectedItem).Row[3].ToString() : string.Empty;
            dr["ES_PurposeName"] = ((DataRowView)this.chkLstBox_Purpose.SelectedItem).Row[1].ToString();
            dr["Source_TextTypeName"] = ((DataRowView)this.chkListBox_Version.SelectedItem).Row[1].ToString();
            dr["IsML"] = dr["EI_Name"].ToString() == "机器学习" ? 1 : 0;
            //if(rbtnInfoNew.==true)
            DataRow[] drr = sysExpressSourceTable.Select(string.Format("Source_ID = '{0}' and Source_ParagraphID = '{1}' and ES_Purpose = '{2}' and Source_TextType = '{3}' ", parentid, sourceParaId, dr["ES_Purpose"], dr["Source_TextType"]));
            if (drr.Length > 0)
            {
                MsgBox.Err("配置表中已存在此规则，请重新选择！");
                clearInput();
                return;
            }
            //数据库中存在此记录
            sysExpressSourceTable.Rows.Add(dr);
            dgvFrmInfoUnit.DataSource = sysExpressSourceTable;
            if (SourceBLL.Exists(dr["CC_ID"].ToString(), dr["Source_ID"].ToString(), dr["Source_ParagraphID"].ToString(), dr["Source_TextType"].ToString(), dr["ES_Purpose"].ToString()))
            {
                this.dgvFrmInfoUnit.Rows[sysExpressSourceTable.Rows.Count - 1].Cells[0].Style.BackColor = this.dgvFrmInfoUnit.Rows[sysExpressSourceTable.Rows.Count - 1].Cells[6].Style.BackColor = this.dgvFrmInfoUnit.Rows[sysExpressSourceTable.Rows.Count - 1].Cells[7].Style.BackColor = this.dgvFrmInfoUnit.Rows[sysExpressSourceTable.Rows.Count - 1].Cells[8].Style.BackColor = this.dgvFrmInfoUnit.Rows[sysExpressSourceTable.Rows.Count - 1].Cells[9].Style.BackColor = System.Drawing.Color.Red;
            }
            dgvFrmInfoUnit.Rows[0].Selected = false;
            clearInput();
        }

        /// <summary>
        /// 双击数据列表，删除数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dgvFrmInfoUnit_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex >= 0 && dgvFrmInfoUnit.Rows.Count > 1 && !string.IsNullOrEmpty(dgvFrmInfoUnit.Rows[e.RowIndex].Cells["ES"].Value.ToString()))
            {
                if (MsgBox.Ask("您确定要删除本条信息吗？") == DialogResult.Yes)
                {

                    dgvFrmInfoUnit.Rows.RemoveAt(e.RowIndex);
                    // int i= sysExpressSourceTable.Rows.Count;
                    //DataRow[] drs=  sysExpressSourceTable.Select("ES_ID="+ dgvFrmInfoUnit.Rows[e.RowIndex].Cells["ES_ID"].Value.ToString());
                    //  sysExpressSourceTable.Rows.Remove(drs[0]);
                }
            }
        }

        /// <summary>
        /// 获取指定text值的节点
        /// </summary>
        /// <param name="tnParent">指定节点</param>
        /// <param name="strText">Text值</param>
        /// <returns></returns>
        private TreeNode FindNodeByText(TreeNode tree, string strText)
        {
            if (tree == null)
            {
                return null;
            }
            if (tree.Text == strText)
            {
                return tree;
            }
            TreeNode tnRet = null;
            foreach (TreeNode item in tree.Nodes)
            {
                tnRet = FindNodeByText(item, strText);
                if (tnRet != null) break;
            }
            return tnRet;
        }

        private TreeNode FindParentNode(TreeNode node)
        {
            if (node.Parent != null && !string.IsNullOrEmpty(node.Parent.Text) && node.Parent.Parent == null)
            {
                return node.Parent;
            }
            else if (node.Parent == null)
            {
                return node;
            }
            else
            {
                return findParentNode(node.Parent);
            }
        }

        /// <summary>
        /// 清空选择内容
        /// </summary>
        public void clearInput()
        {
            //清除用途列表选项
            chkLstBox_Purpose.SelectedItems.Clear();
            //清除版本列表选项
            chkListBox_Version.SelectedItems.Clear();
            //清除来源及逻辑段选项
            Tree_Source.SelectedNode = null;

            groupBox1.Enabled = false;
            Tree_Source.ForeColor = System.Drawing.Color.Gray;
            groupBox9.Enabled = false;
            // groupBox4.Enabled = false;

            rbtnInfoNew.Checked = rbtnInfoCopy.Checked = false;
            lstBox.Enabled = false;
            lstBox.DataSource = null;
            Tree_Source.ForeColor = System.Drawing.Color.Gray;

            dgvFrmInfoUnit.ClearSelection();


        }


        /// <summary>
        /// 确定按钮添加数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSure_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(es_id) && dgvFrmInfoUnit.SelectedRows.Count > 0)
            {
                //批量按钮选中后
                if (rbtnInfoCopy.Checked)
                {
                    if (lstBox.SelectedItems.Count == 0)
                    {
                        MsgBox.Err("请选择共用信息单元后再试！");
                        return;
                    }
                }
                foreach (DataRow dr in sysExpressSourceTable.Rows)
                {
                    if (dr["ES_ID"].ToString() == es_id)
                    {
                        String ccRegexInfoCode = string.Empty;
                        if (rbtnInfoCopy.Checked)
                        {
                            ccRegexInfoCode = lstBox.DataSource != null ? ((DataRowView)lstBox.SelectedItem).Row[0].ToString() : string.Empty;
                        }
                        if (string.IsNullOrEmpty(ccRegexInfoCode))
                        {
                            #region  信息单元
                            Reg_InfoUnit nodeChild = new Reg_InfoUnit();
                            nodeChild.EI_Name = ClickNode.Text;
                            nodeChild.EN_ID = "EI_ID1507221438500001";
                            nodeChild.EI_Remark = "";
                            nodeChild.EI_ID = newid.CreateID("Reg_InfoUnit");
                            nodeChild.EI_Code = nodeChild.EI_ID;//编号==ID 
                            regexbll.AddReg_InfoUnit(nodeChild);
                            ccRegexInfoCode = nodeChild.EI_Code;
                            #endregion
                        }
                        dr["CC_RegexInfoCode"] = ccRegexInfoCode;
                        dr["EI_Name"] = rbtnInfoNew.Checked ? "新增" : lstBox.DataSource != null ? ((DataRowView)lstBox.SelectedItem).Row[3].ToString() : string.Empty;

                    }
                }
                clearInput();
            }
            else if (!ckbInfoUnit.Checked && groupBox1.Enabled == true && groupBox9.Enabled == true)
            {
                //绑定数据列表
                BinddgvFrmInfoUnitData();
            }


        }



        /// <summary>
        /// 用途属性单击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void chkLstBox_Purpose_Click_1(object sender, EventArgs e)
        {
            if (ckbInfoUnit.Checked)
            {
                if (sysExpressSourceDefaultTable != null && sysExpressSourceDefaultTable.Rows.Count > 0)
                {
                    DataRow[] dataRows = sysExpressSourceDefaultTable.Select(" ES_PurposeID='" + this.chkLstBox_Purpose.SelectedValue + "' ");
                    if (dataRows.Length > 0)
                    {
                        foreach (DataRow dr in dataRows)
                        {
                            //从来源默认配置表中添加来源列表信息
                            DataRow drr = sysExpressSourceTable.NewRow();
                            drr["ES_ID"] = newid.JudgeDoc_CreateID("SYS_Express_Source");
                            drr["CC_ID"] = ClickNode.Tag.ToString();
                            drr["Source_ID"] = dr["CD_Code"].ToString();
                            drr["Source_ParagraphID"] = dr["CDL_Code"].ToString();
                            drr["Source_Name"] = dr["CD_Name"].ToString();
                            drr["Source_ParagraphName"] = dr["CDL_Name"].ToString();
                            //var ccRegexInfoCode = lstBox.DataSource != null ? ((DataRowView)lstBox.SelectedItem).Row[1].ToString() : string.Empty;
                            //if (string.IsNullOrEmpty(ccRegexInfoCode))
                            //{
                            //    #region  信息单元
                            //    Reg_InfoUnit nodeChild = new Reg_InfoUnit();
                            //    nodeChild.EI_Name = ClickNode.Text;
                            //    nodeChild.EN_ID = "EI_ID1507221438500001";
                            //    nodeChild.EI_Remark = "";
                            //    nodeChild.EI_ID = newid.CreateID("Reg_InfoUnit");
                            //    nodeChild.EI_Code = nodeChild.EI_ID;//编号==ID 
                            //    regexbll.AddReg_InfoUnit(nodeChild);
                            //    ccRegexInfoCode = nodeChild.EI_Code;
                            //    #endregion
                            //}
                            //dr["CC_RegexInfoCode"] = ccRegexInfoCode;
                            drr["ES_Purpose"] = dr["ES_PurposeID"].ToString();// ((DataRowView)this.chkLstBox_Purpose.SelectedItem).Row[0].ToString();
                            drr["Source_TextType"] = dr["TextType_Code"].ToString();// ((DataRowView)this.chkListBox_Version.SelectedItem).Row[2].ToString();
                            // dr["EI_Name"] = rbtnInfoNew.Checked ? "新增" : lstBox.DataSource != null ? ((DataRowView)lstBox.SelectedItem).Row[3].ToString() : string.Empty;
                            drr["EI_Name"] = "";
                            drr["CC_RegexInfoCode"] = "";
                            drr["ES_PurposeName"] = dr["ES_PurposeName"].ToString();// ((DataRowView)this.chkLstBox_Purpose.SelectedItem).Row[1].ToString();
                            drr["Source_TextTypeName"] = dr["TextType_Name"].ToString();// ((DataRowView)this.chkListBox_Version.SelectedItem).Row[1].ToString();
                            //if(rbtnInfoNew.==true)
                            DataRow[] drr1 = sysExpressSourceTable.Select(string.Format("Source_ID = '{0}' and Source_ParagraphID = '{1}' and ES_Purpose = '{2}' and Source_TextType = '{3}' ", drr["Source_ID"], drr["Source_ParagraphID"], drr["ES_Purpose"], drr["Source_TextType"]));
                            if (drr1.Length == 0)
                            {
                                //MsgBox.Err("配置表中已存在此规则，请重新选择！");
                                //clearInput();
                                //return;
                                sysExpressSourceTable.Rows.Add(drr);
                            }
                        }
                        dgvFrmInfoUnit.DataSource = sysExpressSourceTable;
                        for (int i = 0; i < sysExpressSourceTable.Rows.Count; i++)
                        {
                            if (SourceBLL.Exists(sysExpressSourceTable.Rows[i]["CC_ID"].ToString(), sysExpressSourceTable.Rows[i]["Source_ID"].ToString(), sysExpressSourceTable.Rows[i]["Source_ParagraphID"].ToString(), sysExpressSourceTable.Rows[i]["Source_TextType"].ToString(), sysExpressSourceTable.Rows[i]["ES_Purpose"].ToString()))
                            {
                                this.dgvFrmInfoUnit.Rows[i].Cells[0].Style.BackColor = this.dgvFrmInfoUnit.Rows[i].Cells[6].Style.BackColor = this.dgvFrmInfoUnit.Rows[i].Cells[7].Style.BackColor = this.dgvFrmInfoUnit.Rows[i].Cells[8].Style.BackColor = this.dgvFrmInfoUnit.Rows[i].Cells[9].Style.BackColor = System.Drawing.Color.Red;
                            }
                        }
                        //clearInput();
                        dgvFrmInfoUnit.Rows[0].Selected = false;
                    }
                }
            }
            else
            {
                if (chkLstBox_Purpose.SelectedItems.Count == 1)
                {
                    groupBox1.Enabled = true;
                    Tree_Source.ForeColor = System.Drawing.Color.Black;
                }
                else
                {
                    groupBox1.Enabled = false;
                    Tree_Source.ForeColor = System.Drawing.Color.Gray;
                }
            }
        }

        /// <summary>
        /// 版本属性单击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void chkListBox_Version_Click_1(object sender, EventArgs e)
        {
            if (chkListBox_Version.SelectedItems.Count == 1)
            {
                groupBox4.Enabled = true;
            }
            else
            {
                groupBox4.Enabled = false;
            }
        }

        /// <summary>
        /// 来源及逻辑树选择之后事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Tree_Source_AfterSelect(object sender, TreeViewEventArgs e)
        {
            if (!string.IsNullOrEmpty(this.Tree_Source.SelectedNode.Text))
            {
                groupBox9.Enabled = true;
            }
            else
            {
                groupBox9.Enabled = false;
            }
        }

        /// <summary>
        /// treeView改变颜色事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void treeView1_DrawNode(object sender, DrawTreeNodeEventArgs e)
        {
            e.DrawDefault = true; //我这里用默认颜色即可，只需要在TreeView失去焦点时选中节点仍然突显
            return;
        }

        /// <summary>
        /// 单击单元格
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dgvFrmInfoUnit_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex >= 0 && dgvFrmInfoUnit.Rows.Count > 1 && !string.IsNullOrEmpty(dgvFrmInfoUnit.Rows[e.RowIndex].Cells["ES"].Value.ToString()))
            {
                es_id = dgvFrmInfoUnit.Rows[e.RowIndex].Cells["ES"].Value.ToString();
            }
        }

        private void lstBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            //绑定数据列表
            BinddgvFrmInfoUnitData();

        }

        /// <summary>
        /// 批量添加
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnPiLiangAdd_Click(object sender, EventArgs e)
        {
            if ((rbtnInfoNew.Checked || rbtnInfoCopy.Checked))
            {
                if (MsgBox.Ask("是否给所有信息单元为空的数据添加？") == DialogResult.Yes)
                {
                    if (rbtnInfoNew.Checked)
                    {
                        #region  信息单元
                        Reg_InfoUnit nodeChild = new Reg_InfoUnit();
                        nodeChild.EI_Name = ClickNode.Text;
                        nodeChild.EN_ID = "EI_ID1507221438500001";
                        nodeChild.EI_Remark = "";
                        nodeChild.EI_ID = newid.CreateID("Reg_InfoUnit");
                        nodeChild.EI_Code = nodeChild.EI_ID;//编号==ID 
                        regexbll.AddReg_InfoUnit(nodeChild);
                        string ccRegexInfoCode = nodeChild.EI_Code;
                        #endregion
                        foreach (DataRow dr in sysExpressSourceTable.Rows)
                        {
                            if (string.IsNullOrEmpty(dr["CC_RegexInfoCode"].ToString()))
                            {
                                dr["CC_RegexInfoCode"] = ccRegexInfoCode;
                                dr["EI_Name"] = "新增(批量)";
                            }
                        }
                    }
                    else if (rbtnInfoCopy.Checked)
                    {
                        foreach (DataRow dr in sysExpressSourceTable.Rows)
                        {
                            if (string.IsNullOrEmpty(dr["CC_RegexInfoCode"].ToString()))
                            {
                                var ccRegexInfoCode = lstBox.DataSource != null ? ((DataRowView)lstBox.SelectedItem).Row[0].ToString() : string.Empty;
                                //if (string.IsNullOrEmpty(ccRegexInfoCode))
                                //{
                                //    #region  信息单元
                                //    Reg_InfoUnit nodeChild = new Reg_InfoUnit();
                                //    nodeChild.EI_Name = ClickNode.Text;
                                //    nodeChild.EN_ID = "EI_ID1507221438500001";
                                //    nodeChild.EI_Remark = "";
                                //    nodeChild.EI_ID = newid.CreateID("Reg_InfoUnit");
                                //    nodeChild.EI_Code = nodeChild.EI_ID;//编号==ID 
                                //    regexbll.AddReg_InfoUnit(nodeChild);
                                //    ccRegexInfoCode = nodeChild.EI_Code;
                                //    #endregion
                                //}
                                dr["CC_RegexInfoCode"] = ccRegexInfoCode;
                                dr["EI_Name"] = rbtnInfoNew.Checked ? "新增" : lstBox.DataSource != null ? ((DataRowView)lstBox.SelectedItem).Row[3].ToString() : string.Empty;
                            }
                        }
                    }

                }
            }
            else
            {
                MsgBox.Warn("请先选择信息单元后再试！");
            }
        }

        /// <summary>
        /// 是否使用机器学习 当勾选机器学习时就不使用下面的信息单元配置
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnUseML_Click(object sender, EventArgs e)
        {
            if (chkML.Checked)
            {
                //绑定数据列表
                BinddgvFrmInfoUnitData(1);
            }
            else
            {
                MessageBox.Show("请先勾选机器学习复选框！");
                chkML.Checked = true;
            }
        }
    }
}
